package es.xpt.ysf.convert;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import es.xpt.ysf.model.Item;

public class ItemConverter implements Converter {

	public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value)
			throws ConverterException {
		if (facesContext == null)
			throw new NullPointerException("facesContext");
		if (uiComponent == null)
			throw new NullPointerException("uiComponent");
		return new Item(value, null);
	}

	public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value)
			throws ConverterException {
		if (facesContext == null)
			throw new NullPointerException("facesContext");
		if (uiComponent == null)
			throw new NullPointerException("uiComponent");

		if (value == null) {
			return "";
		}
		
		if (value instanceof Item) {
			return ((Item) value).getCode();
		} else {
			throw new ConverterException("Cannot convert value '" + value + "'");
		}
		
	}

}
